package com.px.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;

public class SmsUtil {
    private static final String SERVER_URL = "https://smssh1.253.com/msg/send/json";
    private static final String ACCOUNT = "N0715120";
    private static final String PASSWORD = "UuNc7zCiPs63f4";

    public static Map sendSms(String phone, String code) {
        String message = MessageFormat.format("【253云通讯】您的验证码为：{0} 此验证码5分钟内有效。", code);

        String reqJson = JsonUtil.toJson(new HashMap<String, String>() {{
            put("account", ACCOUNT);
            put("password", PASSWORD);
            put("msg", message);
            put("phone", phone);
            put("report", "true");
        }});

        String resp = sendSmsByPost(reqJson);
        return JsonUtil.fromJson(resp, Map.class);
    }

    private static String sendSmsByPost(String postContent) {
        URL url;
        try {
            url = new URL(SERVER_URL);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setConnectTimeout(10000);
            httpURLConnection.setReadTimeout(10000);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/json");

            httpURLConnection.connect();
            OutputStream os = httpURLConnection.getOutputStream();
            os.write(postContent.getBytes(StandardCharsets.UTF_8));
            os.flush();

            StringBuilder sb = new StringBuilder();
            int httpRspCode = httpURLConnection.getResponseCode();
            if (httpRspCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), StandardCharsets.UTF_8));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                return sb.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
